//==============================================================================
#include "ClientSender.h"

//==============================================================================
ClientSender::ClientSender(GameClient* client)
{
	setClient(client);
	setIsSending(true);
}
//------------------------------------------------------------------------------
ClientSender::~ClientSender(void)
{
}
//------------------------------------------------------------------------------
void ClientSender::setClient(GameClient* client)
{
	this->client = client;
}
//------------------------------------------------------------------------------
GameClient* ClientSender::getClient()
{
	return this->client;
}
//------------------------------------------------------------------------------
void ClientSender::setIsSending(bool flag)
{
	this->_isSending = flag;
}
//------------------------------------------------------------------------------
bool ClientSender::isSending()
{
	return this->_isSending;
}
//------------------------------------------------------------------------------
DWORD ClientSender::run(void)
{
	return startSendingUpdates();
}
//------------------------------------------------------------------------------
int ClientSender::startSendingUpdates(void)
{	
	ByteBuffer sendBuffer;
	Message* message;
	try
	{
		while (isSending())
		{	
			if(!getClient()->getOutputQueue()->empty()){
				getClient()->getOutputQueueLock()->adquire();
				message = getClient()->getOutputQueue()->front();
				getClient()->getOutputQueue()->pop();
				getClient()->getOutputQueueLock()->release();
				message->marshal(&sendBuffer);
				getClient()->getSocket()->doSendComplete(&sendBuffer);
				delete message;
			}
		}
	}
	catch (NetworkException &ne)
	{
		int errorCode = WSAGetLastError();
		cout << "send failed with error: " << errorCode << endl;
		getClient()->setIsConnectionError(true);
		delete message;
	}
	return 0;
}
//------------------------------------------------------------------------------
void ClientSender::stopSendingUpdates(void)
{
	setIsSending(false);
}